package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jspsmart.upload.SmartUpload;

import Dao.CourseResourceDao;
import Dao.LearningResourceDao;
import Dao.SequenceDao;
import Entity.CourseResource;
import Entity.LearningResource;

/**
 * Servlet implementation class UploadServlet
 */
//@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private ServletConfig config;
	private static final long serialVersionUID = 1L;
	
	final public void init(ServletConfig config) throws ServletException{
		this.config=config;
	}
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");//解决乱码
		response.setContentType("text/html;charset=utf-8");//解决乱码
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		HttpSession session=request.getSession();
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//String courseID1=request.getParameter("courseID1");
       // String opttype=request.getParameter("opttype");
        //System.out.print(opttype);
       
		try {
			SmartUpload su=new SmartUpload();
			//上传初始化
			su.initialize(config, request, response);
			su.upload();
			String uploadType=su.getRequest().getParameter("uploadType");
			String uploader=su.getRequest().getParameter("uploader");
			String fileName=su.getRequest().getParameter("courseName");
			String label=su.getRequest().getParameter("label");
			String courseName=su.getRequest().getParameter("courseName");
			String resourceName=su.getRequest().getParameter("resourceName");
			String uploadTimeYear=su.getRequest().getParameter("uploadTimeYear");
			String uploadTimeMonth=su.getRequest().getParameter("uploadTimeMonth");
			String uploadTimeDay=su.getRequest().getParameter("uploadTimeDay");
			String briefIntroduce=su.getRequest().getParameter("briefIntroduce");
			int totalCount_courseResource=new CourseResourceDao().queryRecordCount();  //获取总条数
			int totalCount_learningResource=new LearningResourceDao().queryRecordCount();
			/*courseID=用户名+上传时间+自动获取序列号*/
			String courseID=(String) session.getAttribute("session_userName")+uploadTimeYear+uploadTimeMonth+uploadTimeDay+new SequenceDao().getCourseResourceIDBySequence();
			/*resourceID=用户名+上传时间+自动获取序列号*/
			String resourceID=(String) session.getAttribute("session_userName")+uploadTimeYear+uploadTimeMonth+uploadTimeDay+new SequenceDao().getLearningIDBySequence();
			//session.setAttribute("session_courseID", courseID);
			String uploadTime=uploadTimeYear+uploadTimeMonth+uploadTimeDay;
			//Date uploadTimeDate=sdf.parse(uploadTime);
			//System.out.println(uploadType+" "+fileName+" "+label+" "+courseName+" "+uploadTimeYear+" "+uploadTimeMonth+" "+uploadTimeDay+" "+briefIntroduce);
			//读取当前网站实际物理路径
			String rootpath=config.getServletContext().getRealPath("/");
			System.out.print(rootpath);
			System.out.println();
			/*根据用户名创建一个目录专门保存用户的图片*/
			java.io.File f=new java.io.File(rootpath+uploader);
			if(!f.exists()) {
				f.mkdir();
			}
			//将上传文件全部保存到指定目录
			int count=su.save(f.getAbsolutePath());
			//逐一提取上传文件信息，同时可保存文件
			for(int i=0;i<su.getFiles().getCount();i++) {
				com.jspsmart.upload.File file=su.getFiles().getFile(i);
				//若文件不存在则继续
				if(file.isMissing()) {
					continue;
				}
				file.saveAs(f.getAbsolutePath()+"/"+file.getFileName(),su.SAVE_PHYSICAL);
				System.out.print(f.getAbsolutePath()+"/"+file.getFileName());
				String filePath=f.getAbsolutePath()+"/"+file.getFileName();
				if(uploadType.equals("CourseResource")) {
				CourseResource cr=new CourseResource(courseID,label,courseName,uploader,uploadTime,filePath,briefIntroduce);//添加数据
				if(new CourseResourceDao().addCourseResource(cr)>0) {
					out.print("<script type='text/javascript'>alert('发布成功！')</script>");
				
				 out.println("<table border='1'>");  
			      out.println("<tr><td>表单选项</td><td>"+file.getFieldName()+"</td></tr>");  
			      out.println("<tr><td>文件长度:</td><td>"+file.getSize()+"</td></tr>");  
			      out.println("<tr><td>文件名</td><td>"+file.getFileName()+"</td></tr>");  
			      out.println("<tr><td>文件扩展名</td><td>"+file.getFileExt()+"</td></tr>");  
			      out.println("<tr><td>文件全名</td><td>"+file.getFilePathName()+"</td></tr>");  
			      out.println("</table><br>");  
			      out.print("用户文件保存成功");	
			}
			}
				else if(uploadType.equals("LearningResource")) {
					LearningResource lr=new LearningResource(resourceID,label,resourceName,uploader,uploadTime,filePath,0,"","",briefIntroduce);//添加数据
					System.out.print(lr.toString());
					if(new LearningResourceDao().addLearningResource(lr)>0) {
						out.print("<script type='text/javascript'>alert('发布成功！')</script>");
						 out.println("<table border='1'>");  
					      out.println("<tr><td>表单选项</td><td>"+file.getFieldName()+"</td></tr>");  
					      out.println("<tr><td>文件长度:</td><td>"+file.getSize()+"</td></tr>");  
					      out.println("<tr><td>文件名</td><td>"+file.getFileName()+"</td></tr>");  
					      out.println("<tr><td>文件扩展名</td><td>"+file.getFileExt()+"</td></tr>");  
					      out.println("<tr><td>文件全名</td><td>"+file.getFilePathName()+"</td></tr>");  
					      out.println("</table><br>");  
					      out.print("用户文件保存成功");	
					}
				}
			
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		
		/*
		 * if(opttype.equals("delete")) { if(new
		 * CourseResourceDao().deleteCourseResourceById(courseID1)>0) {
		 * response.sendRedirect(
		 * "/UniversityResourceSystem/UploadServlet?opttype=showAll"); } }
		 * if(opttype.equals("showAll")) { response.sendRedirect(
		 * "JSP_teacherPersonalManage/myExcellentCourses_teacher.jsp"); }
		 */
		out.flush();
		out.close();
		
	}
	

}
